const Discussion = require('../models/Discussion');
const { Op } = require('sequelize');

class DiscussionService {
  // 获取讨论列表（支持搜索和筛选）
  async getDiscussions({ query = '', packageId = '', sortBy = 'newest', page = 1, pageSize = 20 }) {
    try {
      const offset = (parseInt(page) - 1) * parseInt(pageSize);
      const where = {};
      
      // 添加搜索条件
      if (query) {
        where.content = { [Op.like]: `%${query}%` };
      }
      
      // 添加包筛选条件
      if (packageId) {
        where.package_id = parseInt(packageId);
      }
      
      // 设置排序
      let order;
      switch (sortBy) {
        case 'oldest':
          order = [['created_at', 'ASC']];
          break;
        case 'likes':
          order = [['likes', 'DESC'], ['created_at', 'DESC']];
          break;
        case 'mostComments':
          // 这里需要通过子查询来按评论数排序，暂时用创建时间排序
          order = [['created_at', 'DESC']];
          break;
        case 'newest':
        default:
          order = [['created_at', 'DESC']];
          break;
      }
      
      // 只获取主评论（非回复）
      where.parent_id = null;
      
      const { count, rows } = await Discussion.findAndCountAll({
        where,
        order,
        limit: parseInt(pageSize),
        offset,
        include: [
          {
            model: require('../models/Package'),
            as: 'package',
            attributes: ['id', 'name']
          }
        ]
      });
      
      // 为每个主评论获取回复数量和基本信息
      const discussionsWithReplies = await Promise.all(
        rows.map(async discussion => {
          const repliesCount = await Discussion.count({
            where: {
              parent_id: discussion.id
            }
          });
          
          const discussionData = discussion.toJSON();
          
          return {
            ...discussionData,
            author: discussionData.user_name,
            comments: repliesCount,
            createdAt: discussionData.created_at
          };
        })
      );
      
      return {
        items: discussionsWithReplies,
        total: count,
        pages: Math.ceil(count / pageSize),
        currentPage: parseInt(page)
      };
    } catch (error) {
      console.error('获取讨论列表失败:', error);
      throw new Error('获取讨论列表失败');
    }
  }

  // 获取包的讨论
  async getDiscussionsByPackage(packageId, { page = 1, limit = 20 }) {
    try {
      const offset = (parseInt(page) - 1) * parseInt(limit);
      
      // 首先获取主评论
      const { count, rows } = await Discussion.findAndCountAll({
        where: {
          package_id: packageId,
          parent_id: null
        },
        order: [['created_at', 'desc']],
        limit: parseInt(limit),
        offset
      });
      
      // 为每个主评论获取回复
      const discussionsWithReplies = await Promise.all(
        rows.map(async discussion => {
          const replies = await Discussion.findAll({
            where: {
              parent_id: discussion.id
            },
            order: [['created_at', 'asc']]
          });
          
          return {
            ...discussion.toJSON(),
            replies
          };
        })
      );
      
      return {
        total: count,
        pages: Math.ceil(count / limit),
        currentPage: parseInt(page),
        discussions: discussionsWithReplies
      };
    } catch (error) {
      console.error('获取讨论失败:', error);
      throw new Error('获取讨论失败');
    }
  }

  // 添加讨论或评论
  async addDiscussion(data) {
    try {
      const { packageId, title, content, user_name = 'anonymous', parent_id = null } = data;
      
      if (!content) {
        throw new Error('内容不能为空');
      }
      
      // 如果是主讨论（非回复），需要标题
      if (!parent_id && !title) {
        throw new Error('讨论标题不能为空');
      }
      
      const discussion = await Discussion.create({
        package_id: packageId || null,
        user_name,
        title: parent_id ? null : title, // 回复不需要标题
        content,
        parent_id
      });
      
      return discussion;
    } catch (error) {
      console.error('添加讨论失败:', error);
      throw error;
    }
  }

  // 点赞评论
  async likeDiscussion(id) {
    try {
      const discussion = await Discussion.findByPk(id);
      
      if (!discussion) {
        throw new Error('评论不存在');
      }
      
      discussion.likes += 1;
      await discussion.save();
      
      return { likes: discussion.likes };
    } catch (error) {
      console.error('点赞失败:', error);
      throw error;
    }
  }

  // 删除评论
  async deleteDiscussion(id) {
    try {
      const discussion = await Discussion.findByPk(id);
      
      if (!discussion) {
        throw new Error('评论不存在');
      }
      
      // 如果有回复，也一起删除
      if (discussion.parent_id === null) {
        await Discussion.destroy({
          where: {
            parent_id: id
          }
        });
      }
      
      await discussion.destroy();
      
      return { message: '删除成功' };
    } catch (error) {
      console.error('删除评论失败:', error);
      throw error;
    }
  }

  // 获取评论详情
  async getDiscussionDetail(id) {
    try {
      const discussion = await Discussion.findByPk(id);
      
      if (!discussion) {
        throw new Error('评论不存在');
      }
      
      return discussion;
    } catch (error) {
      console.error('获取评论详情失败:', error);
      throw error;
    }
  }

  // 获取评论的回复
  async getReplies(discussionId) {
    try {
      const replies = await Discussion.findAll({
        where: {
          parent_id: discussionId
        },
        order: [['created_at', 'asc']]
      });
      
      return replies;
    } catch (error) {
      console.error('获取回复失败:', error);
      throw new Error('获取回复失败');
    }
  }

  // 搜索讨论
  async searchDiscussions(keyword, packageId = null, limit = 20) {
    try {
      const where = {};
      
      if (keyword) {
        where.content = { [Op.like]: `%${keyword}%` };
      }
      
      if (packageId) {
        where.package_id = packageId;
      }
      
      const discussions = await Discussion.findAll({
        where,
        order: [['created_at', 'desc']],
        limit
      });
      
      return discussions;
    } catch (error) {
      console.error('搜索讨论失败:', error);
      throw new Error('搜索讨论失败');
    }
  }
}

module.exports = new DiscussionService();